#include "main.h"


#define IP "172.22.238.202"
#define PORT 8080
#define BUFFER_SIZE 1024

int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    socklen_t addrlen = sizeof(address); // 使用socklen_t类型来存储地址长度
    char buffer[BUFFER_SIZE] = {0};
    const char *hello = "Hello from server";
    ssize_t num_bytes_read; // 用于存储read函数读取的字节数

    // 创建socket文件描述符
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 初始化地址和端口
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr(IP);
    address.sin_port = htons(PORT);

    // 绑定socket到端口
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 监听端口
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    printf("Server is listening on port %d\n", PORT);

    // 接受客户端连接
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, &addrlen)) < 0) {
        perror("accept");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    printf("Client connected from IP: %s, Port: %d\n", inet_ntoa(address.sin_addr), ntohs(address.sin_port));

    // 读取客户端消息
    num_bytes_read = read(new_socket, buffer, BUFFER_SIZE - 1); // 减1是为了留出空间给字符串的终结符'\0'
    if (num_bytes_read < 0) {
        perror("read failed");
        close(new_socket);
        close(server_fd);
        exit(EXIT_FAILURE);
    } else if (num_bytes_read == 0) {
        printf("Client closed connection without sending any data.\n");
    } else {
        buffer[num_bytes_read] = '\0'; // 确保字符串以'\0'终结
        printf("Message from client: %s\n", buffer);
    }

    // 发送消息到客户端
    if (send(new_socket, hello, strlen(hello), 0) < 0) {
        perror("send failed");
        close(new_socket);
        close(server_fd);
        exit(EXIT_FAILURE);
    }
    printf("Hello message sent\n");

    // 关闭socket
    close(new_socket);
    close(server_fd);

    return 0;
}